using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class DocumentsOnTable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    [Header("Dragging")]
    public bool dragOnSurfaces = true;
    public bool isDraggingThisDocument;
    private GameObject m_DraggingIcon;
    private RectTransform m_DraggingPlane;
    
    [Header("Change Sprite Between Tables")]
    public Sprite documentBig;
    public Sprite documentSmall;
    private bool isCrossingTable;
    public Transform BigTable_front;
    public Transform SmallTable_front;
    public float SmallTableAndBigTableUIBoarderValue = -0.3f;
    public bool isOnBigTable;

    [Header("Giveback Document")]
    public bool canBeGivenBack;
    public Vector3 mousePosition;
    public GameObject img_GiveBackHint;
    public Transform GiveBackArea_BottomLeftCorner;
    public Transform GiveBackArea_TopRightCorner;
    public float Screen_Bottom = -3.0f;
    public float Screen_Top = 4.3f;
    public float Screen_Left = -8.5f;
    public float Screen_Right = 8.5f;
    
    [Header("Document Falling")]
    public bool isFalling;
    public float fallingSpeed;
    public float stopFallingPositionY;

    [Header("AskMode Related")] 
    public GameObject AskModeClickablePartsGroup;

    private void Start()
    {

    }

    void Update()
    {
        mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        if (isDraggingThisDocument)
        {
            if(mousePosition.x <= SmallTableAndBigTableUIBoarderValue)
            {
                //设置完图片之后，设置尺寸
                transform.parent = SmallTable_front;
                transform.SetSiblingIndex(2);
                gameObject.GetComponent<Image>().sprite = documentSmall;
                gameObject.GetComponent<Image>().SetNativeSize();
                isOnBigTable = false;
                //myRectTransform.sizeDelta = new Vector2(35,45);
            }
            else
            {
                transform.parent = BigTable_front;
                transform.SetSiblingIndex(2);
                gameObject.GetComponent<Image>().sprite = documentBig;
                gameObject.GetComponent<Image>().SetNativeSize();
                isOnBigTable = true;
                //myRectTransform.sizeDelta = new Vector2(180,223);
            }
            
            //当鼠标位于屏幕左侧，且位于人像区的时候，显示GiveBack提示UI；否则提示UI消失
            if (canBeGivenBack)
            {
                if (mousePosition.x <= GiveBackArea_TopRightCorner.position.x &&
                    mousePosition.x >= GiveBackArea_BottomLeftCorner.position.x)
                {
                    if (mousePosition.y <= GiveBackArea_TopRightCorner.position.y &&
                        mousePosition.y >= GiveBackArea_BottomLeftCorner.position.y)
                    {
                        img_GiveBackHint.SetActive(true);
                    }
                    else
                    {
                        img_GiveBackHint.SetActive(false);
                    }
                }
                else
                {
                    img_GiveBackHint.SetActive(false);
                }
            }
        }

        if (isFalling)
        {
            FreeFallToTheTable();
        }
    }
    
    public void OnBeginDrag(PointerEventData eventData)
    {
        if (NPCManager.instance.isInAskMode)
        {
            return;;
        }
        var canvas = FindInParents<Canvas>(gameObject);
        if (canvas == null)
            return;

        // We have clicked something that can be dragged.
        // What we want to do is create an icon for this.
        m_DraggingIcon = gameObject;

        if (dragOnSurfaces)
            m_DraggingPlane = transform as RectTransform;
        else
            m_DraggingPlane = canvas.transform as RectTransform;


        SmallTableBigTableLayering();
        
        SetDraggedPosition(eventData);
        isDraggingThisDocument = true;
    }

    public void OnDrag(PointerEventData data)
    {
        if (NPCManager.instance.isInAskMode)
        {
            return;;
        }
        if (m_DraggingIcon != null)
            SetDraggedPosition(data);

        //SmallTableBigTableLayering();
    }

    private void SetDraggedPosition(PointerEventData data)
    {
        if (dragOnSurfaces && data.pointerEnter != null && data.pointerEnter.transform as RectTransform != null 
            )
            m_DraggingPlane = data.pointerEnter.transform as RectTransform;

        var rt = m_DraggingIcon.GetComponent<RectTransform>();
        Vector3 globalMousePos;
        //y 上边界 4.3; 下边界 -3
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos))
        {
            Vector3 tempPosition = globalMousePos;
            if (mousePosition.x < Screen_Left)
            {
                tempPosition.x = Screen_Left;
            }
            
            if (mousePosition.x > Screen_Right)
            {
                tempPosition.x = Screen_Right;
            }

            if (mousePosition.y < Screen_Bottom)
            {
                tempPosition.y = Screen_Bottom;
            }

            if (mousePosition.y > Screen_Top)
            {
                tempPosition.y = Screen_Top;
            }

            rt.position = tempPosition;
            rt.rotation = m_DraggingPlane.rotation;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (NPCManager.instance.isInAskMode)
        {
            return;;
        }
        SetDraggedPosition(eventData);
        isDraggingThisDocument = false;
        SmallTableBigTableLayering();

        //如果停止拖拽的时候，鼠标处于屏幕左侧小桌子范围，且位于人像区，则文件被归还给NPC
        if (canBeGivenBack)
        {
            if (mousePosition.x <= GiveBackArea_TopRightCorner.position.x &&
                mousePosition.x >= GiveBackArea_BottomLeftCorner.position.x)
            {
                if (mousePosition.y <= GiveBackArea_TopRightCorner.position.y &&
                    mousePosition.y >= GiveBackArea_BottomLeftCorner.position.y)
                {
                    Destroy(gameObject);
                    NPCManager.instance.currentNPC.GetComponent<NPCController>().GiveBackDocument();
                }
            }
        }
        
        
        //如果停止拖拽的时候，鼠标处于小桌子范围，且不可被返还，则执行自由落体事件
        if (mousePosition.x <= SmallTableAndBigTableUIBoarderValue)
        {
            isFalling = true;
        }
    }

    static public T FindInParents<T>(GameObject go) where T : Component
    {
        if (go == null) return null;
        var comp = go.GetComponent<T>();

        if (comp != null)
            return comp;

        Transform t = go.transform.parent;
        while (t != null && comp == null)
        {
            comp = t.gameObject.GetComponent<T>();
            t = t.parent;
        }
        return comp;
    }

    public void SmallTableBigTableLayering()
    {
        //设置前后遮挡的逻辑
        if(mousePosition.x <= SmallTableAndBigTableUIBoarderValue)
        {
            transform.parent = SmallTable_front;
            transform.SetSiblingIndex(2);
        }
        else
        {
            transform.parent = BigTable_front;
            transform.SetSiblingIndex(2);
        }
    }

    public void FreeFallToTheTable()
    {
        Vector3 tempPosition = gameObject.GetComponent<RectTransform>().position;
        tempPosition.y -= fallingSpeed;
        gameObject.GetComponent<RectTransform>().position = tempPosition;
        if (gameObject.GetComponent<RectTransform>().position.y <= stopFallingPositionY)
        {
            isFalling = false;
        }
    }
}
